<template>
  <div>
    <el-dialog
      title="执行任务"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="42%"
      v-dialog-drag
      :close-on-click-modal="false"
      top="3vh"
      class="report-text-form"
      @close="handleClose()"
      @open="handleOpen()"
    >
      <div slot="title" class="dialog-title">
        <span class='title'>执行任务</span>
        <el-button type="primary" plain :loading="saveloading" @click="handleTransfer">转 办</el-button>
      </div>
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="90px">
        <el-form-item label="任务名称">
          <div class="text-value">{{taskDetail.taskName}}</div>
        </el-form-item>

        <el-form-item label="任务内容">
          <div class="text-value">{{taskDetail.taskDes}}</div>
        </el-form-item>

        <el-form-item label="附件">
          <template v-if='taskDetail.orderFiles && taskDetail.orderFiles.length'>
            <div class="text-value" v-for="item in taskDetail.orderFiles" :key='item.id'>
              <el-link type="primary" :underline="false" @click="handlePreview(item)">{{item.name}}</el-link>
            </div>
          </template>
          <div v-else>-</div>
        </el-form-item>

        <el-form-item label="所属工厂">
          <div class="text-value">{{taskDetail.factoryDeptName}}</div>
        </el-form-item>

        <el-form-item label="所属车间">
          <div class="text-value">{{taskDetail.workshopName}}</div>
        </el-form-item>

        <el-form-item label="所属产线" class="line">
          <div class="text-value">{{taskDetail.lineName}}</div>
        </el-form-item>

        <el-divider></el-divider>

        <el-form-item label="任务阶段" prop="taskStage">
          <el-radio-group v-model="form.taskStage">
            <el-radio :label="1">跟进阶段</el-radio>
            <el-radio :label="2">执行完毕，待提交审核</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="参与人" prop="partInUserName">
          <el-input type="text" v-model="form.partInUserName" maxlength="100" show-word-limit placeholder="请输入参与人"></el-input>
        </el-form-item>

        <el-form-item :label='form.taskStage ==1 ? "跟进结果" : "执行结果"' prop="execResultDes">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4}"
            maxlength="1000"
            show-word-limit
            placeholder="请输入执行结果"
            v-model="form.execResultDes">
          </el-input>
        </el-form-item>

        <el-form-item label="附件">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="{Authorization:token}"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-upload='beforeAvatarUpload'
            :on-success='handleSuccess'
            :accept="acceptFile"
            multiple
            :limit="10"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请上传大小不超过 5MB 格式为 jpg/png/gif/pdf/doc/docx/xls/xlsx/ppt/pptx/jpeg/zip 的文件，最多10个。</div>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="saveloading" @click="handleSave" v-if='form.taskStage ==1'>保存跟进</el-button>
        <el-button type="primary" :loading="saveloading" @click="handleSubmit" v-if='form.taskStage ==2'>提交审核</el-button>
      </span>
    </el-dialog>
    <transfer-dialog
      :visible.sync="transferDialog.visible"
      :row="transferDialog.row"
      @submit-success="submitTransfer"
    />
  </div>
</template>
<script>
  import axios from 'axios'
  import { getToken } from '@/utils/auth'
  import service from "../../../utils/request";
  import { GEN_SERVER } from '@/config/baseUrl'
  import { downloadFile } from '@/utils/file'
  import { parseTime } from '@/utils/eam'
  import { fileTypes } from '@/utils/file'
  import {taskExecute,taskSave,taskDetail} from "@/api/leanTask/report";
  import transferDialog from "./transferDialog";
export default {
  components:{transferDialog},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default: ()=>{}
    }
  },
  data() {
    return {
      form: {
        id:null,
        taskStage:null,
        partInUserName:null,
        execResultDes:null,
        execFileIds:[]
      },
      fileTypes,
      fileList:[],
      rules: {
        taskStage:[
          { required: true, message: "请选择任务阶段", trigger: "change" },
        ],
        partInUserName: [
          { required: true, message: "请输入参与人", trigger: "blur" },
        ],
        execResultDes: [
          { required: true, message: "请输入执行结果", trigger: "blur" }
        ]
      },
      taskDetail:{},
      transferDialog: {
        visible: false,
        row: null,
      },

      saveloading: false
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val)
      },
      get() {
        return this.visible
      }
    },
    uploadUrl(){
      return service.baseURL + GEN_SERVER['form-server'] + '/refine/report/upload'
    },
    token() {
      return 'Bearer ' + getToken()
    },
    acceptFile(){
      return Object.values(this.fileTypes).join(",")
    }
  },
  methods: {
    handleClose() {
      this.saveloading = false
      this.resetFormData()
    },

    handleOpen() {
      this.resetFormData();
      this.form.id = this.row.id;
      this.$set(this.form,"taskStage",1)
      this.getTaskDetail();
    },

    getTaskDetail(){
      taskDetail(this.row.id)
      .then(res=>{
        if (res.code == 200 && res.data) {
          this.taskDetail = res.data;
          this.form.partInUserName = res.data.partInUserName;
          this.form.execResultDes = res.data.execResultDes;
          this.form.execFileIds = res.data.execFileIds;
          if(res.data.files?.length){
            this.fileList = res.data.files.map(item => {
              return {
                name: item?.fileName,
                response: {
                  data: item.id,
                  code: 200
                }
              };
            });
          }
          if(this.taskDetail?.orderFiles?.length){
            this.$nextTick(() => {
              this.taskDetail.orderFiles = this.taskDetail.orderFiles.map(item => {
                return{
                  name: item?.fileName,
                  id:item.id,
                  response: {
                    data: item.id,
                    code: 200
                  }
                }
              })
            })
          }
        } else {
          this.taskDetail = {};
          this.fileList = [];
          this.resetFormData()
        }
      }).catch(() => {
        this.resetFormData()
      })
    },

    handleSubmit() {
      this.saveloading = true
      this.$refs.ruleForm
      .validate((flag) => {
        if (flag) {
          taskExecute(this.form).then(res => {
            if (res.code == 200) {
              this.msgSuccess("操作成功")
              this.$emit("submit-success")
              this.dialogVisible = false
            } else {
              this.msgError(res.msg || "操作失败")
            }
            this.saveloading = false
          }).catch(() => {
            this.msgError("操作失败")
            this.saveloading = false
          })
        } else {
          this.saveloading = false
        }
      })
    },

    //暂存
    handleSave(){
      this.saveloading = true
      this.$refs.ruleForm
      .validate((flag) => {
        if (flag) {
          taskSave(this.form).then(res => {
            if (res.code == 200) {
              this.msgSuccess("操作成功")
              this.$emit("submit-success")
              this.dialogVisible = false
            } else {
              this.msgError(res.msg || "操作失败")
            }
            this.saveloading = false
          }).catch(() => {
            this.msgError("操作失败")
            this.saveloading = false
          })
        } else {
          this.saveloading = false
        }
      })
    },

    handleTransfer() {
      this.transferDialog.row = this.row;
      this.transferDialog.visible = true;
    },

    submitTransfer(){
      this.$emit("submit-success");
      this.transferDialog.visible = false;
      this.dialogVisible = false;
    },

    handleSuccess(response, file, fileList){
      this.fileList = fileList;
      this.form.execFileIds = fileList.map(ele => ele.response?.data)
    },

    handleRemove(file, fileList) {
      this.fileList = fileList;
      if(fileList?.length){
        this.form.execFileIds = fileList.map(ele => ele.response?.data)
      }else{
        this.form.execFileIds = []
      }
    },

    getObjectURL(file) {
      var url = null;
      if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file);
      } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file);
      } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file);
      }
      return url;
    },

    handlePreview(file) {
      if(file.raw){
        var previewUrl = this.getObjectURL(file.raw);
        location.href = previewUrl;
      }else{
        axios({
          baseURL:service.baseURL + GEN_SERVER['form-server'],
          url:'/refine/report/byte/down',
          method:"get",
          params:{id:file?.response?.data},
          headers: {Authorization:'Bearer ' + getToken()},
          responseType: 'blob'
        }).then(res => {
          let count = file.name.lastIndexOf(".");
          let fileName = file.name.slice(0,count);
          let suffix = file.name.slice(count);
          downloadFile(res.data,`${fileName}${parseTime(new Date(), '{y}{m}{d}')}${suffix}`)
          this.saveloading = false
        }).catch(() => {
          this.msgError("操作失败")
          this.saveloading = false
        })
      }
    },

    beforeAvatarUpload(file){
      if(!this.acceptFile.includes(file.type)){
        this.msgWarning("暂不支持上传该格式文件");
        return false
      }
      if(file.size / 1024 / 1024  > 5){
        this.msgWarning("上传的附件大小不得超过5M");
        return false
      }
    },

    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 10个文件，本次选择了 ${files.length} 个文件`);
      return false
    },

    resetFormData() {
      this.$refs.ruleForm?.resetFields()
      this.form = {
        id:null,
        partInUserName:null,
        execResultDes:null,
        execFileIds:[]
      };
      this.fileList = [];
    },
  }
};
</script>
<style lang="scss" scoped>
.el-form {
  .el-date-editor.el-input,
  .el-select {
    width: 100%;
  }
}
.tool-bar{
  margin-bottom:20px
}
.text-value{
  font-size: 0.875rem;
  line-height:2.25rem;
  color:#666
}
.report-text-form{
  ::v-deep .el-dialog .el-dialog__body{
    max-height: calc(100vh - 16rem);
    .line{
      margin-bottom:0;
    }
    .el-divider--horizontal{
      margin:16px 0
    }
  }
}
.dialog-title{
  display:flex;
  align-items: center;
  justify-content: space-between;
  .title{
    line-height: 1.5rem;
    font-size: 1.125rem;
    color: #303133;
  }
  button{
    margin-right: 40px;
  }
}

</style>
